#!/bin/bash

# 设置颜色和样式
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'

# 进度条函数
show_progress() {
    local width=50
    local progress=0
    
    echo -n "["
    for ((i=0; i<width; i++)); do
        echo -n " "
    done
    echo -n "] 0%"
    
    for ((i=0; i<=width; i++)); do
        progress=$((i * 100 / width))
        echo -ne "\r["
        for ((j=0; j<i; j++)); do
            echo -n "▓"
        done
        for ((j=i; j<width; j++)); do
            echo -n " "
        done
        echo -n "] $progress%"
        sleep 0.1
    done
    echo
}

# 显示欢迎界面
clear
echo -e "${CYAN}${BOLD}"
cat << "EOF"
 █████╗ ███████╗████████╗██████╗ ██████╗  ██████╗ ████████╗
██╔══██╗██╔════╝╚══██╔══╝██╔══██╗██╔══██╗██╔═══██╗╚══██╔══╝
███████║███████╗   ██║   ██████╔╝██████╔╝██║   ██║   ██║   
██╔══██║╚════██║   ██║   ██╔══██╗██╔══██╗██║   ██║   ██║   
██║  ██║███████║   ██║   ██║  ██║██████╔╝╚██████╔╝   ██║   
╚═╝  ╚═╝╚══════╝   ╚═╝   ╚═╝  ╚═╝╚═════╝  ╚═════╝    ╚═╝   
EOF
echo -e "${NC}"
echo -e "${BLUE}${BOLD}智能机器人部署系统 - 高级安装向导${NC}\n"

echo -e "${CYAN}[1/4]${NC} 系统初始化检查..."
show_progress 100

# 配置 yum 源并安装必要工具
echo -e "\n${CYAN}[2/4]${NC} 配置系统环境..."

# 备份原有源
echo -e "${YELLOW}备份原有 yum 源...${NC}"
mkdir -p /etc/yum.repos.d/backup
mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup/ &> /dev/null || true

# 检查 git 是否已安装
if command -v git &> /dev/null; then
    echo -e "${GREEN}✓ git 已安装: $(git --version)${NC}"
else
    # 安装 git
    echo -e "${YELLOW}安装 git...${NC}"
    
    # 配置 CentOS 7 的源
    cat > /etc/yum.repos.d/CentOS-Base.repo << 'EOF'
[base]
name=CentOS-$releasever - Base
baseurl=https://mirrors.aliyun.com/centos/7/os/$basearch/
gpgcheck=0
enabled=1

[updates]
name=CentOS-$releasever - Updates
baseurl=https://mirrors.aliyun.com/centos/7/updates/$basearch/
gpgcheck=0
enabled=1

[extras]
name=CentOS-$releasever - Extras
baseurl=https://mirrors.aliyun.com/centos/7/extras/$basearch/
gpgcheck=0
enabled=1
EOF

    # 清理并重建缓存
    yum clean all &> /dev/null
    yum makecache &> /dev/null

    # 安装 git
    if ! yum install -y git &> /dev/null; then
        echo -e "${RED}yum 安装 git 失败，尝试手动安装...${NC}"
        (
            cd /tmp || exit 1
            wget -q https://mirrors.aliyun.com/centos/7/os/x86_64/Packages/git-1.8.3.1-23.el7_8.x86_64.rpm
            rpm -ivh --nodeps --force git-1.8.3.1-23.el7_8.x86_64.rpm &> /dev/null
            rm -f git-1.8.3.1-23.el7_8.x86_64.rpm
        )
        
        # 验证 git 安装
        if ! command -v git &> /dev/null; then
            echo -e "${RED}git 安装失败${NC}"
            exit 1
        fi
        echo -e "${GREEN}✓ git 安装成功: $(git --version)${NC}"
    fi
fi

show_progress 50

# 配置 Docker 镜像加速和网络设置
echo -e "\n${CYAN}[3/4]${NC} 配置 Docker 加速器..."
mkdir -p /etc/docker
cat > /etc/docker/daemon.json <<EOF
{
    "registry-mirrors": [
        "https://docker.1ms.run",
        "https://mirror.ccs.tencentyun.com",
        "https://hub-mirror.c.163.com",
        "https://mirror.baidubce.com",
        "https://dockerproxy.com"
    ],
    "dns": ["223.5.5.5", "223.6.6.6", "8.8.8.8"],
    "max-concurrent-downloads": 10,
    "max-concurrent-uploads": 5,
    "log-driver": "json-file",
    "log-opts": {
        "max-size": "100m",
        "max-file": "3"
    },
    "default-address-pools": [
        {
            "base": "172.16.0.0/16",
            "size": 24
        }
    ]
}
EOF

# 配置系统 DNS
cat > /etc/resolv.conf <<EOF
nameserver 223.5.5.5
nameserver 223.6.6.6
nameserver 8.8.8.8
EOF

# 重启 Docker 服务并等待就绪
echo -e "\n${CYAN}[4/4]${NC} 应用配置并启动服务..."
systemctl daemon-reload
systemctl restart docker

# 等待 Docker 服务就绪
echo -e "${YELLOW}等待 Docker 服务就绪...${NC}"
for i in {1..60}; do
    if docker info &> /dev/null; then
        break
    fi
    sleep 2
done

# 测试 Docker 镜像拉取
echo -e "${YELLOW}测试 Docker 镜像拉取...${NC}"
for i in {1..3}; do
    if docker pull hello-world &> /dev/null; then
        break
    fi
    echo -e "${YELLOW}第 $i 次尝试拉取镜像...${NC}"
    sleep 5
done

show_progress 80

# 切换到根目录
cd /root || exit 1
echo -e "\n${BOLD}开始部署 AstrBot...${NC}"

# 检查 unzip 是否已安装
if ! command -v unzip &> /dev/null; then
    echo -e "${YELLOW}unzip 未安装，正在安装...${NC}"
    yum install -y unzip &> /dev/null || {
        echo -e "${RED}安装 unzip 失败${NC}"
        exit 1
    }
    echo -e "${GREEN}✓ unzip 安装成功${NC}"
fi

# 删除可能存在的旧目录
if [ -d "/AstrBot" ]; then
    rm -rf /AstrBot
fi

# 下载并解压 AstrBot 仓库
echo -e "${YELLOW}镜像由方云智算提供 下载 AstrBot 仓库...${NC}"
wget --progress=bar:force https://mirror.fangyunidc.cn/github.php?git=Soulter/AstrBot -O /tmp/AstrBot.zip || {
    echo -e "${RED}下载失败${NC}"
    exit 1
}

# 解压 ZIP 文件到根目录
echo -e "${YELLOW}镜像由方云智算提供 解压 AstrBot...${NC}"
cd / || exit 1
unzip -o -q /tmp/AstrBot.zip || {
    echo -e "${RED}解压失败${NC}"
    exit 1
}

# 重命名文件夹
mv AstrBot-master AstrBot || {
    echo -e "${RED}重命名文件夹失败${NC}"
    exit 1
}

# 切换到 AstrBot 目录
cd AstrBot || {
    echo -e "${RED}切换目录失败${NC}"
    exit 1
}

# 删除未使用的变量声明
PWD=$(pwd)
echo -e "${YELLOW}当前工作目录: ${PWD}${NC}"

# 修改 docker-compose.yml
COMPOSE_FILE=$(find . -name "docker-compose.yml" -o -name "compose.yml" | head -n 1)
if [ -n "$COMPOSE_FILE" ]; then
    echo -e "${YELLOW}找到配置文件: ${COMPOSE_FILE}${NC}"
    
    # 创建新的 compose.yml 文件
    cat > "$COMPOSE_FILE" <<EOF
services:
  astrbot:
    image: soulter/astrbot:latest
    container_name: astrbot
    ports: 
      - "6180-6200:6180-6200"
      - "11451:11451"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - ./data:/AstrBot/data
    restart: unless-stopped
EOF
    echo -e "${GREEN}✓ 配置文件更新完成${NC}"
else
    echo -e "${RED}错误: 未找到 docker-compose.yml 或 compose.yml 文件${NC}"
    exit 1
fi

# 启动服务前确认配置文件存在
if [ ! -f "$COMPOSE_FILE" ]; then
    echo -e "${RED}错误: 配置文件不存在: ${COMPOSE_FILE}${NC}"
    exit 1
fi

# Docker 服务检查和启动函数
check_docker_service() {
    echo -e "${YELLOW}检查 Docker 服务状态...${NC}"
    
    # 如果 Docker 已经在运行，直接返回
    if docker info &> /dev/null; then
        echo -e "${GREEN}Docker 服务已在运行${NC}"
        return 0
    fi
    
    # 检查 Docker 是否安装
    if ! command -v docker &> /dev/null; then
        echo -e "${RED}Docker 未安装，请先安装 Docker${NC}"
        return 1
    fi
    
    # 尝试修复 Docker 服务
    echo -e "${YELLOW}尝试修复 Docker 服务...${NC}"
    
    # 停止服务
    systemctl stop docker containerd
    
    # 清理 Docker 资源
    echo -e "${YELLOW}清理 Docker 资源...${NC}"
    rm -rf /var/lib/docker/*
    rm -rf /var/run/docker*
    rm -rf /var/run/containerd/*
    
    # 重新创建目录
    mkdir -p /var/lib/docker
    mkdir -p /etc/docker
    
    # 重置 Docker 配置
    echo -e "${YELLOW}重置 Docker 配置...${NC}"
    cat > /etc/docker/daemon.json <<EOF
{
    "registry-mirrors": [
        "https://docker.1ms.run",
        "https://mirror.ccs.tencentyun.com",
        "https://hub-mirror.c.163.com",
        "https://mirror.baidubce.com",
        "https://dockerproxy.com"
    ],
    "dns": ["223.5.5.5", "223.6.6.6", "8.8.8.8"],
    "max-concurrent-downloads": 10,
    "max-concurrent-uploads": 5,
    "log-driver": "json-file",
    "log-opts": {
        "max-size": "100m",
        "max-file": "3"
    }
}
EOF
    
    # 重新加载系统服务
    echo -e "${YELLOW}重新加载系统服务...${NC}"
    systemctl daemon-reload
    
    # 启动 containerd
    echo -e "${YELLOW}启动 containerd...${NC}"
    systemctl start containerd || {
        echo -e "${RED}containerd 启动失败${NC}"
        return 1
    }
    
    # 启动 Docker
    echo -e "${YELLOW}启动 Docker...${NC}"
    systemctl start docker || {
        echo -e "${RED}Docker 启动失败，查看详细日志：${NC}"
        journalctl -xe --unit docker.service | tail -n 20
        return 1
    }
    
    # 等待服务就绪
    for i in {1..5}; do
        if docker info &> /dev/null; then
            echo -e "${GREEN}Docker 服务已就绪${NC}"
            return 0
        fi
        echo -n "."
        sleep 2
    done
    
    echo -e "${RED}Docker 服务启动超时${NC}"
    return 1
}

# 在启动服务前检查 Docker
if ! check_docker_service; then
    echo -e "${RED}Docker 服务问题无法解决，请手动检查${NC}"
    exit 1
fi

# 清理旧容器
echo -e "${YELLOW}清理旧容器...${NC}"
docker system prune -f &> /dev/null

# 镜像拉取函数，带重试和多镜像源
pull_image() {
    local image_name=$1
    local max_retries=3
    local mirrors=(
        "dockerproxy.com"
        "docker.nju.edu.cn"
        "docker.mirrors.ustc.edu.cn"
        ""  # 直接从官方源拉取
    )

    for mirror in "${mirrors[@]}"; do
        for ((i=1; i<=max_retries; i++)); do
            echo -e "${YELLOW}尝试从 ${mirror:-官方源} 拉取镜像 (第 $i 次)...${NC}"
            if [ -n "$mirror" ]; then
                full_image="${mirror}/${image_name}"
            else
                full_image="${image_name}"
            fi

            if docker pull "$full_image"; then
                if [ -n "$mirror" ]; then
                    # 如果使用了镜像源，重新标记为原始镜像名
                    docker tag "$full_image" "$image_name"
                    docker rmi "$full_image"
                fi
                return 0
            fi
            sleep 3
        done
    done
    return 1
}

# 修改镜像拉取部分
echo -e "${YELLOW}拉取 AstrBot 镜像...${NC}"
if ! pull_image "soulter/astrbot:latest"; then
    echo -e "${RED}所有镜像源均尝试失败，请检查网络连接${NC}"
    exit 1
fi

# 启动服务
echo -e "${YELLOW}启动 AstrBot 服务...${NC}"
if docker compose -f "$COMPOSE_FILE" up -d; then
    echo -e "\n${GREEN}容器启动中...${NC}"
    
    # 等待容器完全启动
    echo -e "${YELLOW}等待服务就绪...${NC}"
    for i in {1..30}; do
        if docker ps | grep -q "astrbot.*Up.*"; then
            echo -e "${GREEN}✓ 服务已就绪${NC}"
            break
        fi
        echo -n "."
        sleep 2
    done
else
    echo -e "${RED}部署失败，错误信息：${NC}"
    docker compose -f "$COMPOSE_FILE" logs
    exit 1
fi

# 获取本地IP
LOCAL_IP=$(ip addr show | grep -w inet | grep -v 127.0.0.1 | awk '{print $2}' | cut -d/ -f1)

# 如果本地IP以17开头，直接使用
if echo "$LOCAL_IP" | grep -q "^17"; then
    SERVER_IP=$LOCAL_IP
else
    # 否则获取本地IP的第三段
    LOCAL_IP=$(echo "$LOCAL_IP" | grep ^192)
    SUBNET=$(echo "$LOCAL_IP" | cut -d. -f3)
    # 查找对应的 17X.${SUBNET} 开头的IP
    SERVER_IP=$(ifconfig | grep -B1 "inet 17" | grep inet | awk '{print $2}' | grep "^17.*\.${SUBNET}\.")
fi

# 显示完成界面
clear
echo -e "${GREEN}${BOLD}"
cat << "EOF"
✨ 部署完成！AstrBot 已成功启动 ✨
EOF
echo -e "${NC}"

echo -e "${CYAN}==================================${NC}"
echo -e "${BOLD}管理面板访问地址：${NC}"
echo -e "${BLUE}▶ http://${SERVER_IP}:6185${NC}"
echo -e "${BLUE}▶ http://localhost:6185${NC}"
echo -e "\n${YELLOW}默认凭据：${NC}"
echo -e "用户名：${BOLD}astrbot${NC}"
echo -e "密码：  ${BOLD}astrbot${NC}"
echo -e "${CYAN}==================================${NC}"

echo -e "\n${GREEN}服务状态：${NC}"
cd /AstrBot && docker compose ps

echo -e "\n${YELLOW}提示：${NC}"
echo -e "1. 如需查看日志，请使用命令：${BOLD}docker compose logs -f${NC}"
echo -e "2. 如需停止服务，请使用命令：${BOLD}docker compose down${NC}"
echo -e "3. 如需重启服务，请使用命令：${BOLD}docker compose restart${NC}"

exit 0